package com.dw.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.config.MinioConfig;
import com.dw.entity.OrderInfo;
import com.dw.feign.ProductFeign;
import com.dw.mapper.OrderMapper;
import com.dw.service.OrderService;
import io.minio.*;
import io.minio.http.Method;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Transient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
* @author deeps
* @description 针对表【order】的数据库操作Service实现
* @createDate 2025-08-16 11:44:32
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo>
    implements OrderService {

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    MinioConfig minioConfig;

    @Autowired
    MinioClient minioClient;

    /**
     * minio 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        // 1. 检查存储桶是否存在，不存在则创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucket()).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucket()).build());
        }

        // 2. 生成唯一文件名
        String originalFilename = file.getOriginalFilename(); // example.txt
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); // .txt
        String objectName = DateUtil.today().replace("-", "")+"/"+UUID.randomUUID().toString() + fileExtension; // 随机字符串 + .txt

        // 3. 上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConfig.getBucket()) // 存储桶名称
                        .object(objectName) // 对象名称（文件名，可以包含目录，test/随机字符串.txt）
                        .stream(file.getInputStream(), file.getSize(), -1) // 文件流，文件大小，每次读取
                        .contentType(file.getContentType()) // 文件类型，比如 image/jpeg
                        .build());

        return objectName;
    }

    /**
     * @param objectFile 对象文件
     * @return {@link String }
     * @Description 根据文件名和桶获取文件路径
     */
    @Override
    public String getFileUrl(String objectFile,int expires) {
        try {

            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(minioConfig.getBucket())
                    .object(DateUtil.today().replace("-", "")+"/"+objectFile)
                    .expiry(expires, TimeUnit.SECONDS)
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public void hello() {
        System.out.println("hello=================");
    }

    @Override
    //@GlobalTransactional
    public void makeOrder()  {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(1);
        orderInfo.setOrderSn("111");
        orderInfo.setOrderStats("1");
        this.save(orderInfo);
        int i = productFeign.reduceProduct();
//        if(i==1){
//            System.out.println("下单成功=================");
//        }else{
//            throw new RuntimeException("下单失败=================");
//        }

    }


}




